from gseapy import Biomart
import pandas as pd
import anndata
from cellphonedb.src.core.methods import cpdb_statistical_analysis_method

work_dir="/public/home/xxf2019/20220915_gastric_multiple/dna_combinePublic/finalPlot/revise/im_favored"
input_file=work_dir + "/immuneCell_cpdb/IM_MUC6.Pit_Immune.h5ad"
output_counts_file=work_dir + "/IM_MUC6.Pit_Immune.cellphonedb2.h5ad"
output_meta_file=work_dir + "/meta_file.csv"
cpdb_file="/public/home/xxf2019/20220915_gastric_multiple/dna_combinePublic/public_ref/singleCell/cellphonedb.zip"
out_path=work_dir + "/immuneCell_cpdb"

adata = anndata.read_h5ad(input_file)
adata_raw=adata.raw.to_adata()
bdata=anndata.AnnData(X=adata_raw.X,
    obs=pd.DataFrame({'cell_type':adata_raw.obs.celltype},index=adata_raw.obs_names),
    var=pd.DataFrame(index=adata_raw.var_names)
    )

bdata.write_h5ad(output_counts_file,compression='lzf')

#####meta data
meta_file = pd.DataFrame({'Cell':bdata.obs.index,'cell_type':bdata.obs.cell_type})
meta_file.to_csv(output_meta_file,index=False)
####删除不需要的变量
del adata,bdata


## https://github.com/ventolab/cellphonedb-data/blob/master/cellphonedb.zip
deconvoluted, means, pvalues, significant_means = cpdb_statistical_analysis_method.call(
    cpdb_file_path = cpdb_file,            
    meta_file_path = output_meta_file ,              
    counts_file_path = output_counts_file,
    counts_data = 'hgnc_symbol',                     
    microenvs_file_path = None,                      
    iterations = 1000,                              
    threshold = 0.1,                                
    threads = 1,                                    
    debug_seed = 42,                                 
    result_precision = 3,                           
    pvalue = 0.05,                                   
    subsampling = False,                             
    subsampling_log = False,                         
    subsampling_num_pc = 100,                        
    subsampling_num_cells = 1000,                    
    separator = '|',                                 
    debug = False,                                   
    output_path = out_path,                             
    output_suffix = "IM_MUC6")
    

'''
## 可视化
import pandas as pd
import scanpy as sc
import datatable as dt
import matplotlib.pyplot as plt
import ktplotspy as kpy

## 用于cellphonedb的adata文件
adata = sc.read_h5ad(output_counts_file)

mean_file=out_path + "statistical_analysis_means_IM_MUC6.txt"
pvals_file=out_path + "statistical_analysis_pvalues_IM_MUC6.txt"
decon_file=out_path + "statistical_analysis_deconvoluted_IM_MUC6.txt"

## 读取cellphonedb的输出文件
means = pd.read_table(mean_file)
pvals = pd.read_table(pvals_file)
decon = pd.read_table(decon_file)

kpy.plot_cpdb_heatmap(
        adata=adata,
        pvals=pvals,
        celltype_key="cell_type", ## adata.obs中细胞类型那一列列名
        figsize = (5,5),
        title = "Sum of significant interactions"
        ## symmetrical = True ## 显得对称
    );

out_name=out_path + "IM_MUC6.cpdb.heatmap.pdf"
plt.savefig(out_name, dpi=300, bbox_inches = 'tight')
plt.show()

kpy.plot_cpdb(
    adata=adata,
    cell_type1="Pit_Mut",
    cell_type2=".",
    means=means,
    pvals=pvals,
    max_size=8,
    max_highlight_size=2,
    celltype_key="cell_type",
    gene_family = "chemokines",
    figsize = (15,10),
    title = "interacting interactions!"
    )
out_name=out_path + "IM_MUC6.cpdb.chemokines.pdf"
plt.savefig(out_name, dpi=300, bbox_inches = 'tight')
plt.show()

kpy.plot_cpdb(
    adata=adata,
    cell_type1="Pit_Mut|Pit_Other|Enterocytes",
    cell_type2="Pit_Mut|Pit_Other|Enterocytes",
    means=means,
    pvals=pvals,
    celltype_key="cell_type",
    highlight_size=1,
    figsize=(4, 5),
    plot_type='simple'
    )
out_name=out_path + "IM_MUC6.cpdb.Mut_Other.pdf"
plt.savefig(out_name, dpi=300, bbox_inches = 'tight')
plt.show()
'''